// 用于无论从那个页面打开进入支付页面，也能在支付成功后正确的返回首页或（指定页面）并且不保存后退历史记录
import Router from 'vue-router'
import Vue from 'vue'

const 重置到首页 = (to, from, next) => {
  if (重置到首页.replaceName) {
    const name = 重置到首页.replaceName
    重置到首页.replaceName = null
    next({...to, name, replace: true})
    return true
  }
}
/*
* 回退到指定name的路由
* @param { string } 路由名称
* */
window.backToName = Router.prototype.backToName = async function (name) {
  const routes = Vue.prototype.$navigation.getRoutes().reverse().map(x => x.split('?')[0])
  const getIndex = name => -Math.max(routes.findIndex(x => x == name), 0)
  let index = getIndex(name)
  console.log(name, routes, index)
  if (routes.length == 1) {  // 只开了一页
    router.replace({name})
    sleep().then(x => sessionStorage.HaveBeenTo = location.href)
    return
  }
  if (index == 0) { // 历史记录没有,回退到首页
    router.go(-routes.length)
    sleep().then(x => sessionStorage.HaveBeenTo = location.href)
    return
  }
  router.go(index) // 有记录
}

export default 重置到首页